package com.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.dubbo.server.enums.CommentType;
import com.dubbo.server.enums.IdType;
import com.dubbo.server.service.IdService;
import com.dubbo.server.service.TimeLineService;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.*;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    IdService idService;
    @Autowired
    TimeLineService timeLineService;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    /**
     * 查询用户时间表
     * @param userId 用户id
     * @param page 当前页数
     * @param pageSize 每一页查询的数据条数
     * @return
     */
    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        Pageable pageable=PageRequest.of(page-1,pageSize,
                Sort.by(Sort.Order.desc("date")));
        Query query=new Query().with(pageable);
        List<TimeLine> timeLines = mongoTemplate.find(query, TimeLine.class,"quanzi_time_line_"+userId);
        if(CollUtil.isEmpty(timeLines))
            return pageInfo;
        List<Object> publishId = CollUtil.getFieldValues(timeLines, "publishId");
        Query query1=Query.query(Criteria.where("id").in(publishId)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishes = mongoTemplate.find(query1, Publish.class);
        pageInfo.setRecords(publishes);
        if(pageInfo==null)
            log.error("pageinfo为空-------------------------");
        return pageInfo;


    }

    /**
     * 查询推荐动态
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */

    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> Info = new PageInfo<>();
        Info.setPageNum(page);
        Info.setPageSize(pageSize);
        String key="QUANZI_PUBLISH_RECOMMEND_" + userId;
        String data = redisTemplate.opsForValue().get(key);

        if(StringUtils.isEmpty(data))
            return Info;
        String[] split = data.split(",");
        int[] ints = PageUtil.transToStartEnd(page - 1, pageSize);
        int start=ints[0];
        int end=Math.min(ints[1],split.length );
        ArrayList<Long> publishes = new ArrayList<>();
        for (int i = start; i <end; i++) {
            publishes.add(Long.valueOf(split[i]));
        }
        Query query=Query.query(Criteria.where("pid").in(publishes));
        List<Publish> publishes1 = mongoTemplate.find(query, Publish.class);
        if(publishes1==null)
            return Info;
        Info.setRecords(publishes1);
        return Info;


    }

    /**
     * 保存动态到数据库
     * @param publish
     * @return
     */

    @Override
    public String savePublish(Publish publish) {
        if(publish.getUserId()==null|| StringUtils.isEmpty(publish.getText()))
            return null;//publsh字符无效
        publish.setId(ObjectId.get());
        publish.setCreated(System.currentTimeMillis());
        publish.setPid(idService.createId(IdType.PUBLISH));
        Album album = new Album();
        album.setCreated(System.currentTimeMillis());
        album.setId(ObjectId.get());
        album.setPublishId(publish.getId());
        try {
            Publish save = mongoTemplate.save(publish);
            mongoTemplate.save(album,"quanzi_album_" + publish.getUserId());
            timeLineService.saveTimeLine(publish.getUserId(),publish.getId());
        } catch (Exception e) {
            log.error("发布动态失败---publish"+publish);
            e.printStackTrace();
        }
        return publish.getId().toHexString();

    }

    /**
     *
     * @param id 动态id
     * @return
     */

    @Override
    public Publish queryPublishById(String id) {
        Publish byId = mongoTemplate.findById(new ObjectId(id), Publish.class);
        if(byId==null)
            log.warn("byId-----------------为空");
        return byId;
    }

    /**
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean likeComment(Long userId, String publishId) {
        try {
            if(queryUserIsLike(userId,publishId))
                return true;
            boolean b = saveComment(userId, publishId, CommentType.LIKE, null);
            if(!b)
                return false;
            String redisKey = this.getCommentRedisKeyPrefix(publishId);
            String hashKey = CommentType.LIKE.toString();
            Long increment = redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
            String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
            redisTemplate.opsForHash().put(redisKey,userHashKey,"1");
        } catch (Exception e) {
           log.error("likeComment出错");
            return false;
        }
        return true;



    }

    private String getCommentUserLikeRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LIEK_REDIS_KEY_PREFIX+userId;
    }

    private String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    /**
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        if(!queryUserIsLike(userId,publishId))
            return true;
      boolean a=removeComment(userId,publishId,CommentType.LIKE);
      if(!a)
          return false;
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        Long increment = redisTemplate.opsForHash().increment(redisKey, hashKey, -1);
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        redisTemplate.opsForHash().delete(redisKey,userHashKey);
        return true;

    }

    private boolean removeComment(Long userId, String publishId,CommentType commentType) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType())
        );
        return this.mongoTemplate.remove(query, Comment.class).getDeletedCount() > 0;
    }

    /**
     *
     * @param publishId
     * @return
     */

    @Override
    public Long queryLikeCount(String publishId) {
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        Object o = redisTemplate.opsForHash().get(redisKey, hashKey);
        if(ObjectUtil.isNotEmpty(o))
            return Convert.toLong(o);
        Long count = this.queryCommentCount(publishId, CommentType.LIKE);
        redisTemplate.opsForHash().put(redisKey,hashKey,String.valueOf(count));
        return count;

    }

    private Long queryCommentCount(String publishId, CommentType like) {
        Query query = new Query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(like.getType()));
        long count = mongoTemplate.count(query, Comment.class);
        return count;
    }

    /**
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        Object o = redisTemplate.opsForHash().get(redisKey, userHashKey);
        if (ObjectUtil.isNotEmpty(o)) {
            return StrUtil.equals(Convert.toStr(o), "1");
        }
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("publishId").is(publishId).and("commentType").is(CommentType.LIKE));
        long count = mongoTemplate.count(query, Comment.class);
        if(count==0)
            return false;

        redisTemplate.opsForHash().put(redisKey,userHashKey,"1");
        return true;

    }


    public boolean saveComment(Long userId, String publishId, CommentType commentType, String
                                 content){
        try {
            Comment comment = new Comment();
            comment.setId(ObjectId.get());
            comment.setUserId(userId);
            comment.setPublishId(new ObjectId(publishId));
            // 评论类型
            comment.setCommentType(commentType.getType());
            // 内容
            comment.setContent(content);
            comment.setCreated(System.currentTimeMillis());
            Publish publish = this.queryPublishById(publishId);

            if(ObjectUtil.isNotEmpty(publish))
                comment.setPublishUserId(publish.getUserId());
            else
            {
                Comment comment2=queryCommentbyId(publishId);
                if(ObjectUtil.isNotEmpty(comment2))
                comment.setPublishUserId(comment2.getUserId());
                else
                {
                    Video  video=queryVideobyId(publishId);
                    if(ObjectUtil.isNotEmpty(video))
                        comment.setPublishUserId(video.getUserId());
                    else
                        return false;

                }

                ;
            }

            Comment save = mongoTemplate.save(comment);
            return true;
        } catch (Exception e) {
            log.error("saveComment出错Long userId, String publishId, CommentType commentType, String\n" +
                    "                                 content"+userId+publishId+commentType
            +content+e);
            return false;
        }


    }

    private Video queryVideobyId(String publishId) {
        Video byId = mongoTemplate.findById(publishId, Video.class);
        return byId;
    }

    private Comment queryCommentbyId(String publishId) {

        Comment byId = mongoTemplate.findById(publishId, Comment.class);
        return byId;
    }



    /*
    * 下面开始是喜欢动态只在推荐列表中
    *jjjjjjjjjjjjjjjjjjjjj
    * */



    public Boolean loveComment(Long userId, String publishId) {
        //查询该用户是否已经喜欢
        if (this.queryUserIsLove(userId, publishId)) {
            return false;
        }

        //喜欢
        boolean result = this.saveComment(userId, publishId, CommentType.LOVE, null);
        if (!result) {
            return false;
        }

        //喜欢成功后，修改Redis中的总的喜欢数
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        //标记用户已经喜欢
        hashKey = this.getCommentUserLoveRedisKey(userId);
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        return true;
    }

    private String getCommentUserLoveRedisKey(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }

    @Override
    public Boolean disLoveComment(Long userId, String publishId) {
        if (!this.queryUserIsLove(userId, publishId)) {
            //如果用户没有喜欢，就直接返回
            return false;
        }

        boolean result = this.removeComment(userId, publishId, CommentType.LOVE);
        if (!result) {
            //删除失败
            return false;
        }

        //删除redis中的记录
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        this.redisTemplate.opsForHash().delete(redisKey, hashKey);
        this.redisTemplate.opsForHash().increment(redisKey, CommentType.LOVE.toString(), -1);

        return true;
    }

    @Override
    public Long queryLoveCount(String publishId) {
        //首先从redis中命中，如果命中的话就返回，没有命中就查询Mongodb
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        Object value = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)) {
            return Convert.toLong(value);
        }

        //查询count
        Long count = this.queryCommentCount(publishId, CommentType.LOVE);

        //存储到redis中
        this.redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));

        return count;
    }

    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        Object value = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)) {
            return StrUtil.equals(Convert.toStr(value), "1");
        }

        //查询mongodb
        Query query = Query.query(Criteria.where("publishId")
                .is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LOVE.getType()));
        long count = this.mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            return false;
        }

        //标记用户已经喜欢
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        return true;
    }

    /**
     * 查询评论
     * @param publishId
     * @param page
     * @param pageSize
     * @return
     */

    @Override
    public PageInfo<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("created")));
        Query query = new Query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.COMMENT.getType())
        ).with(pageRequest);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        PageInfo<Comment> commentPageInfo = new PageInfo<>();
         commentPageInfo.setRecords(comments);
         commentPageInfo.setPageNum(page);
         commentPageInfo.setPageSize(pageSize);
         return commentPageInfo;

    }

    /**
     * 保存评论
     * @param userId
     * @param publishId
     * @param content
     * @return
     */
    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {
       return saveComment(userId,publishId,CommentType.COMMENT,content);
    }

    /**
     * 查询评论总数
     * @param vid
     * @return
     */

    @Override
    public Long queryCommentCount(String vid) {
        Long aLong = queryCommentCount(vid, CommentType.COMMENT);
        return aLong;
    }

    @Override
    public PageInfo<Comment> queryLikeCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId,CommentType.LIKE,page,pageSize);
    }

    @Override
    public PageInfo<Comment> queryLoveCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId,CommentType.LOVE,page,pageSize);
    }

    @Override
    public PageInfo<Comment> queryCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId,CommentType.COMMENT,page,pageSize);
    }
    public PageInfo<Comment> queryCommentListByUser(Long userId, CommentType commentType,Integer page, Integer pageSize){
        PageRequest created = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query publishId = Query.query(Criteria.where("publishUserId").is(userId).and("commentType").is(commentType.getType())).with(created);
        List<Comment> comments = mongoTemplate.find(publishId, Comment.class);
        PageInfo<Comment> pageInfo=new PageInfo<>();
        pageInfo.setRecords(comments);
        return pageInfo;

    }

    @Override
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        PageRequest pageRequest = PageRequest.of(page - 1 , pageSize,
                Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);
        List<Album> albumList = this.mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        List<Object> publishIdList = CollUtil.getFieldValues(albumList, "publishId");

        Query queryPublish = Query.query(Criteria.where("id").in(publishIdList))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);
        pageInfo.setRecords(publishList);
        return pageInfo;

    }
}
